package com.grj.parkingsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grj.parkingsystem.entity.ParkingSpace;
import com.grj.parkingsystem.service.ParkingLotService;
import com.grj.parkingsystem.service.ParkingSpaceService;
import com.grj.parkingsystem.mapper.ParkingSpaceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author ganru
* @description 针对表【t_parking_space(车位表)】的数据库操作Service实现
* @createDate 2025-05-16 16:51:44
*/
@Service
public class ParkingSpaceServiceImpl extends ServiceImpl<ParkingSpaceMapper, ParkingSpace>
    implements ParkingSpaceService{
    @Autowired
    private ParkingLotService parkingLotService;

    @Override
    public List<ParkingSpace> getAvailableSpaces(Long parkingLotId) {
        return baseMapper.selectList(new QueryWrapper<ParkingSpace>()
                .eq("parking_lot_id", parkingLotId)
                .eq("status", 0)); // 0: 空闲
    }

    @Override
    @Transactional
    public boolean reserveSpace(Long spaceId) {
        ParkingSpace space = baseMapper.selectById(spaceId);
        if (space == null || space.getStatus() != 0) {
            return false;
        }

        space.setStatus(3); // 3: 已预订
        boolean success = updateById(space);

        if (success) {
            // 更新停车场可用车位数量
            parkingLotService.updateAvailableSpaces(space.getParkingLotId(), -1);
        }

        return success;
    }

    @Override
    @Transactional
    public boolean releaseSpace(Long spaceId) {
        ParkingSpace space = baseMapper.selectById(spaceId);
        if (space == null || (space.getStatus() != 1 && space.getStatus() != 3)) {
            return false;
        }

        space.setStatus(0); // 0: 空闲
        boolean success = updateById(space);

        if (success) {
            // 更新停车场可用车位数量
            parkingLotService.updateAvailableSpaces(space.getParkingLotId(), 1);
        }

        return success;
    }
}




